from Queue import Queue
import threading
class CThread(threading.Thread):
    def __init__(self, queue, call):
        threading.Thread.__init__(self)
        self.job = queue
        self.threadCall=call
        
    def run(self):
        while True:
            self.threadCall(self.job.get())
            self.job.task_done()

class TaskQueue(Queue):
    def __init__(self):
        Queue.__init__(self)        
        self.all_tasks_done = threading.Condition(self.mutex)
        self.unfinished_tasks = 0

    def _put(self, item):
        Queue._put(self, item)
        self.unfinished_tasks += 1        

    def task_done(self):
        self.all_tasks_done.acquire()
        try:
            unfinished = self.unfinished_tasks - 1
            if unfinished <= 0:
                if unfinished < 0:
                    raise ValueError('task_done() called too many times')
                self.all_tasks_done.notifyAll()
            self.unfinished_tasks = unfinished
        finally:
            self.all_tasks_done.release()

    def join(self):
        self.all_tasks_done.acquire()
        try:
            while self.unfinished_tasks:
                self.all_tasks_done.wait()
        finally:
            self.all_tasks_done.release()



job = TaskQueue()

def initThread(num,threadCall):
    for i in range(num):
        t = CThread(job,threadCall)
        t.setDaemon(True)
        t.start()   

def putjob(ajob):
    job.put(ajob)

def waitDone():
    job.join()



